#!/bin/sh /etc/rc.common
# Copyright (C) 2019 Ycarus (Yannick Chabanois) <ycarus@zugaina.org> for OpenMPTCProuter project

START=90
STOP=10

USE_PROCD=1
PROG_NAME=dsvpn
PROG=/usr/sbin/${PROG_NAME}

_log() {
	logger -p daemon.info -t ${PROG_NAME} "$@"
}

_err() {
	logger -p daemon.err -t ${PROG_NAME} "$@"
}

validate_section() {
	uci_validate_section dsvpn dsvpn "${1}" \
		'enable:bool:0'       \
		'key:string'          \
		'host:host'           \
		'port:port'           \
		'dev:string'          \
		'localip:host'        \
		'remoteip:host'       \
		'mode:string:client'  \
		'externalip:string:auto'
}

start_instance() {
	local enable key host port dev

	validate_section "${1}" || {
		_err "validation failed"
		return 1
	}

	[ "${enable}" = "1" ] || return 1

	[ -n "${key}" ] || return 1
	[ "${key}" != "secretkey" ] || return 1
	[ -z "${host}" ] && host="auto"
	[ -z "${port}" ] && port="auto"
	[ -n "${dev}" ] || return 1

	echo "${key}" > /tmp/${PROG_NAME}-${1}.key
	key=""

	if [ "$(uci -q get network.omrvpn)" != "" ] && [ "$(uci -q get network.omrvpn)" != "$dev" ]; then
		uci -q set network.omrvpn.ifname=$dev
		uci -q commit
	fi

	ip addr flush $dev
	sleep 2

	_log "starting ${PROG_NAME} ${1} instance $*"

	procd_open_instance

	procd_set_param command ${PROG} ${mode} \
		/tmp/${PROG_NAME}-${1}.key \
		$host \
		$port \
		$dev  \
		${localip:+$localip} \
		${remoteip:+$remoteip}
	[ "$mode" = "client" ] && procd_append_param command $(ip r get $host | awk '{print $3}' | tr -d "\n")
	[ "$mode" = "server" ] && procd_append_param command externalip


	procd_set_param respawn 0 30 5
	procd_set_param file /tmp/${PROG_NAME}-${1}.key

	procd_set_param stdout 1
	procd_set_param stderr 1

	procd_close_instance


}

start_service() {
	config_load dsvpn
	config_foreach start_instance dsvpn
}

service_triggers() {
	procd_add_reload_trigger dsvpn network
}
